<template>
    <div class="profile-page">
        <Header />
        
        <PageBanner
            title="个人中心"
            subtitle="管理您的个人信息和账户设置"
            :breadcrumbs="[
                { title: '个人中心' }
            ]"
        />
        
        <div class="container">
            <div class="content-wrapper">
                <div class="profile-container">
            <div class="profile-sidebar">
                <div class="profile-info">
                    <div class="avatar">
                                <el-avatar :size="80" :src="getAvatarUrl(userInfo.avatar, defaultAvatar)" @error="onImageError" :data-original-src="userInfo.avatar">
                            {{ userInfo.nickname?.charAt(0) || userInfo.username?.charAt(0) }}
                        </el-avatar>
                    </div>
                    <div class="user-details">
                        <h3>{{ userInfo.nickname || userInfo.username }}</h3>
                        <p>{{ userInfo.email || '未设置邮箱' }}</p>
                        <p>{{ userInfo.phone || '未设置手机号' }}</p>
                    </div>
                </div>
                
                <div class="menu-list">
                    <div 
                        v-for="(item, index) in filteredMenuItems" 
                        :key="index"
                        class="menu-item"
                        :class="{ active: activeMenu === item.key }"
                        @click="activeMenu = item.key"
                    >
                        <el-icon>
                            <component :is="item.icon"></component>
                        </el-icon>
                        <span>{{ item.label }}</span>
                    </div>
                            
                            <!-- 临时调试按钮 -->
                            <div class="menu-item" @click="debugUserRoles">
                                <el-icon><InfoFilled /></el-icon>
                                <span>调试角色</span>
                    </div>
                </div>
            </div>
            
            <div class="profile-main">
                <!-- 基本信息 -->
                <div v-if="activeMenu === 'basic'" class="tab-content">
                    <h2>基本信息</h2>
                    <el-form 
                        :model="userForm" 
                        :rules="rules" 
                        ref="userFormRef" 
                        label-width="80px"
                    >
                                <el-form-item label="头像">
                                    <div class="avatar-uploader-container">
                                        <el-upload
                                            class="avatar-uploader"
                                            action="#"
                                            :http-request="uploadAvatar"
                                            :show-file-list="false"
                                            :before-upload="beforeAvatarUpload"
                                        >
                                            <img v-if="avatarUrl" :src="avatarUrl" class="avatar-preview" @error="onImageError" :data-original-src="avatarUrl" />
                                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                                        </el-upload>
                                        <div class="avatar-tips">
                                            <p>点击上传头像</p>
                                            <p>建议上传正方形图片</p>
                                        </div>
                                    </div>
                                </el-form-item>
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="userForm.username" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="昵称" prop="nickname">
                            <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                
                <!-- 安全设置 -->
                <div v-if="activeMenu === 'security'" class="tab-content">
                    <h2>安全设置</h2>
                    <el-form 
                        :model="passwordForm" 
                        :rules="passwordRules" 
                        ref="passwordFormRef" 
                        label-width="120px"
                    >
                        <el-form-item label="原密码" prop="oldPassword">
                            <el-input 
                                v-model="passwordForm.oldPassword" 
                                type="password"
                                placeholder="请输入原密码"
                                show-password
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="新密码" prop="newPassword">
                            <el-input 
                                v-model="passwordForm.newPassword" 
                                type="password"
                                placeholder="请输入新密码"
                                show-password
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="确认新密码" prop="confirmPassword">
                            <el-input 
                                v-model="passwordForm.confirmPassword" 
                                type="password"
                                placeholder="请再次输入新密码"
                                show-password
                            ></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="changePassword">修改密码</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                
                <!-- 账户管理 -->
                <div v-if="activeMenu === 'account'" class="tab-content">
                    <h2>账户管理</h2>
                    <el-card shadow="hover">
                        <div class="account-option">
                            <div>
                                <h3>注销账户</h3>
                                <p>注销账户将删除您的所有数据，且无法恢复</p>
                            </div>
                            <el-button type="danger" @click="confirmDeleteAccount">注销账户</el-button>
                        </div>
                    </el-card>
                        </div>

                        <!-- 我的房源 -->
                        <div v-if="activeMenu === 'myhouses'" class="tab-content">
                            <div class="myhouses-header">
                                <h2>我的房源</h2>
                                <el-button type="primary" @click="showUploadHouseDialog">发布新房源</el-button>
                            </div>

                            <div class="house-status-tabs">
                                <el-tabs v-model="houseStatusTab" @tab-click="handleTabChange">
                                    <el-tab-pane label="全部房源" name="all"></el-tab-pane>
                                    <el-tab-pane label="审核中" name="0"></el-tab-pane>
                                    <el-tab-pane label="在售中" name="1"></el-tab-pane>
                                    <el-tab-pane label="已售出" name="2"></el-tab-pane>
                                    <el-tab-pane label="已下架" name="3"></el-tab-pane>
                                    <el-tab-pane label="审核未通过" name="4"></el-tab-pane>
                                </el-tabs>
                            </div>

                            <div v-loading="houseLoading">
                                <!-- 没有房源的提示 -->
                                <el-empty v-if="filteredUserHouses.length === 0" description="暂无房源数据">
                                    <el-button type="primary" @click="showUploadHouseDialog">立即发布</el-button>
                                </el-empty>

                                <!-- 房源列表 -->
                                <div v-else class="user-house-list">
                                    <el-card v-for="house in filteredUserHouses" :key="house.id" class="house-card" shadow="hover">
                                        <div class="house-card-header">
                                            <div class="house-title">{{ house.title }}</div>
                                            <div class="house-status">
                                                <el-tag v-if="house.status === '0'" type="warning">审核中</el-tag>
                                                <el-tag v-else-if="house.status === '1'" type="success">在售中</el-tag>
                                                <el-tag v-else-if="house.status === '2'" type="info">已售出</el-tag>
                                                <el-tag v-else-if="house.status === '3'" type="danger">已下架</el-tag>
                                                <el-tag v-else-if="house.status === '4'" type="danger">审核未通过</el-tag>
                                            </div>
                                        </div>
                                        <div class="house-info">
                                            <div class="house-image">
                                                <img :src="house.image || '/src/assets/images/default-house.jpg'" alt="房源图片" @error="onHouseImageError">
                                            </div>
                                            <div class="house-details">
                                                <div class="house-price">{{ house.price }}</div>
                                                <div class="house-area">{{ house.area }}</div>
                                                <div class="house-address">{{ house.address }}</div>
                                                <div class="house-time">发布时间: {{ house.createTime }}</div>
                                                <div v-if="house.status === '4'" class="house-reject-reason">
                                                    未通过原因: {{ house.rejectReason || '审核未通过，请修改后重新提交' }}
                                                </div>
                                            </div>
                                        </div>
                                        <div class="house-actions">
                                            <el-button size="small" type="primary" @click="viewHouseDetail(house)">查看详情</el-button>
                                            <el-button size="small" type="warning" @click="editHouse(house)" :disabled="house.status === '2'">编辑</el-button>
                                            <el-button size="small" type="danger" @click="removeHouse(house)">删除</el-button>
                                        </div>
                                    </el-card>
                                </div>

                                <!-- 分页 -->
                                <div class="pagination" v-if="filteredUserHouses.length > 0">
                                    <el-pagination
                                        background
                                        layout="prev, pager, next"
                                        :total="houseStatusTab === 'all' ? totalHouses : filteredUserHouses.length"
                                        :page-size="5"
                                        @current-change="handleHousePageChange"
                                    />
                                </div>
                            </div>

                            <!-- 上传房源对话框 -->
                            <el-dialog
                                v-model="uploadHouseDialogVisible"
                                title="发布新房源"
                                width="60%"
                                :before-close="handleDialogClose"
                            >
                                <el-form :model="houseForm" :rules="houseRules" ref="houseFormRef" label-width="100px">
                                    <el-form-item label="房源标题" prop="title">
                                        <el-input v-model="houseForm.title" placeholder="请输入房源标题"></el-input>
                                    </el-form-item>
                                    <el-form-item label="房源价格" prop="price">
                                        <el-input v-model="houseForm.price" placeholder="例如: 300万"></el-input>
                                    </el-form-item>
                                    <el-form-item label="房源面积" prop="area">
                                        <el-input v-model="houseForm.area" placeholder="例如: 120㎡"></el-input>
                                    </el-form-item>
                                    <el-form-item label="地址" prop="address">
                                        <el-input v-model="houseForm.address" placeholder="请输入详细地址"></el-input>
                                    </el-form-item>
                                    <el-form-item label="房源简介" prop="description">
                                        <el-input type="textarea" v-model="houseForm.description" rows="4" placeholder="请输入房源简介"></el-input>
                                    </el-form-item>
                                    <el-form-item label="房源图片">
                                        <el-upload
                                            action="#"
                                            list-type="picture-card"
                                            :http-request="uploadHouseImage"
                                            :file-list="houseImageList"
                                            :on-preview="handleImagePreview"
                                            :on-remove="handleImageRemove"
                                            :before-upload="beforeHouseImageUpload"
                                            multiple
                                        >
                                            <el-icon><Plus /></el-icon>
                                        </el-upload>
                                        <el-dialog v-model="imagePreviewVisible" title="图片预览">
                                            <img :src="previewImageUrl" alt="预览" style="width: 100%">
                                        </el-dialog>
                                    </el-form-item>
                                </el-form>
                                <template #footer>
                                    <span class="dialog-footer">
                                        <el-button @click="uploadHouseDialogVisible = false">取消</el-button>
                                        <el-button type="primary" @click="submitHouseForm" :loading="submitting">
                                            {{ houseForm.id ? '更新房源' : '发布房源' }}
                                        </el-button>
                                    </span>
                                </template>
                            </el-dialog>
                        </div>

                        <!-- 添加管理中心内容 -->
                        <div v-if="activeMenu === 'management'" class="tab-content">
                            <h2>管理中心</h2>
                            <p>欢迎使用吉居房产系统管理中心</p>
                            <div class="management-panel">
                                <el-row :gutter="20">
                                    <el-col :span="8">
                                        <el-card shadow="hover" class="management-card" @click="navigateTo('/admin/houses')">
                                            <div class="management-card-content">
                                                <div class="management-icon-wrapper">
                                                    <el-icon :size="30"><HomeFilled /></el-icon>
                                                </div>
                                                <h3>房源管理</h3>
                                                <p>管理所有房源信息</p>
                                            </div>
                                        </el-card>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-card shadow="hover" class="management-card" @click="navigateTo('/admin/house-assign')">
                                            <div class="management-card-content">
                                                <div class="management-icon-wrapper">
                                                    <el-icon :size="30"><Setting /></el-icon>
                                                </div>
                                                <h3>房源分配</h3>
                                                <p>管理房源分配记录</p>
                                            </div>
                                        </el-card>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-card shadow="hover" class="management-card" @click="navigateTo('/admin/view-records')">
                                            <div class="management-card-content">
                                                <div class="management-icon-wrapper">
                                                    <el-icon :size="30"><UserFilled /></el-icon>
                                                </div>
                                                <h3>经纪人审核</h3>
                                                <p>审核经纪人申请</p>
                                            </div>
                                        </el-card>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-card shadow="hover" class="management-card" @click="navigateTo('/admin/login-logs')">
                                            <div class="management-card-content">
                                                <div class="management-icon-wrapper">
                                                    <el-icon :size="30"><User /></el-icon>
                                                </div>
                                                <h3>登录日志</h3>
                                                <p>用户登录记录</p>
                                            </div>
                                        </el-card>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-card shadow="hover" class="management-card" @click="navigateTo('/admin/oper-logs')">
                                            <div class="management-card-content">
                                                <div class="management-icon-wrapper">
                                                    <el-icon :size="30"><Document /></el-icon>
                                                </div>
                                                <h3>操作日志</h3>
                                                <p>系统操作记录</p>
                                            </div>
                                        </el-card>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-card shadow="hover" class="management-card" @click="navigateTo('/admin/settings')">
                                            <div class="management-card-content">
                                                <div class="management-icon-wrapper">
                                                    <el-icon :size="30"><Tools /></el-icon>
                                                </div>
                                                <h3>系统设置</h3>
                                                <p>系统参数配置</p>
                                            </div>
                                        </el-card>
                                    </el-col>
                                </el-row>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <Footer />
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateUserInfo as updateUserAPI, changePassword as changePasswordAPI } from '@/api/user'
import { getHouseList, deleteHouse } from '@/api/house'
import defaultAvatar from '@/assets/images/default-avatar.jpg'
import { useRouter } from 'vue-router'
import { Plus, InfoFilled, HomeFilled, Tools, View, UserFilled, User, Document, Setting } from '@element-plus/icons-vue'
import { getAvatarUrl, getFullImageUrl } from '@/utils/imageUrl'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'
import PageBanner from '@/views/common/PageBanner.vue'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo || {})
const router = useRouter()

// 添加调试信息，查看用户信息
console.log('当前用户信息:', userInfo.value)

// 菜单项配置
const menuItems = [
    { label: '基本信息', key: 'basic', icon: 'User' },
    { label: '安全设置', key: 'security', icon: 'Lock' },
    { label: '账户管理', key: 'account', icon: 'Setting' },
    { label: '管理中心', key: 'management', icon: 'Tools', roles: ['admin', 'agent'] },
    { key: 'myhouses', label: '我的房源', icon: 'HomeFilled' }, // 保留我的房源菜单
]

// 过滤菜单项，根据用户角色显示
const filteredMenuItems = computed(() => {
    // 获取用户角色
    const roles = userStore.roles || []
    console.log('当前用户角色:', roles)
    
    const items = menuItems.filter(item => {
        // 如果菜单项没有roles属性，所有用户都可见
        if (!item.roles) return true
        
        // 如果菜单项有roles属性，检查用户是否有对应角色
        const hasRole = item.roles.some(role => roles.includes(role))
        console.log(`菜单项 ${item.label} 是否显示:`, hasRole)
        
        return hasRole
    })

    return items
})

const activeMenu = ref('basic')
const userFormRef = ref(null)
const passwordFormRef = ref(null)
const houseFormRef = ref(null)
const avatarUrl = ref('')
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
const houseLoading = ref(false)
const uploadHouseDialogVisible = ref(false)
const submitting = ref(false)
const houseStatusTab = ref('all')
const currentHousePage = ref(1)
const totalHouses = ref(0) // 总房源数
const houseRules = {
  title: [
    { required: true, message: '请输入房源标题', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 个人信息表单
const userForm = reactive({
    username: '',
    nickname: '',
    email: '',
    phone: '',
    avatar: ''
})

// 修改密码表单
const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

// 表单校验规则
const rules = {
    nickname: [
        { required: false, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: false, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
        { required: false, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
}

const passwordRules = {
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { 
            validator: (rule, value, callback) => {
                if (value !== passwordForm.newPassword) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            }, 
            trigger: 'blur' 
        }
    ]
}

// 初始化表单数据
onMounted(async () => {
    // 先尝试获取最新用户信息
    await userStore.getInfo()
    
    console.log('载入用户信息:', userStore.userInfo)
    console.log('用户角色:', userStore.roles)
    
    if (userStore.userInfo) {
        userForm.username = userStore.userInfo.username || ''
        // 优先使用nickName字段，这是后端返回的字段名
        userForm.nickname = userStore.userInfo.nickName || userStore.userInfo.nickname || ''
        userForm.email = userStore.userInfo.email || ''
        userForm.phone = userStore.userInfo.phone || userStore.userInfo.phoneNumber || ''
        
        // 使用工具函数处理头像URL
        avatarUrl.value = getAvatarUrl(userStore.userInfo.avatar, defaultAvatar)
        console.log('设置头像URL:', avatarUrl.value)
    }

    // 获取用户房源数据
    fetchUserHouses()
})

// 更新个人信息
const updateUserInfo = async () => {
    if (!userFormRef.value) return
    
    try {
        await userFormRef.value.validate()
        
        // 创建要提交的数据对象
        const submitData = {
            username: userForm.username,
            // 提交时使用nickName字段而不是nickname，匹配后端API
            nickName: userForm.nickname || '',
            email: userForm.email || '',
            phone: userForm.phone || '',
            // 确保包含用户ID
            id: userInfo.value?.userId || userInfo.value?.id || ''
        }
        
        // 更新表单中的头像字段
        if (avatarUrl.value && avatarUrl.value !== defaultAvatar) {
            submitData.avatar = avatarUrl.value
        } else if (userInfo.value?.avatar) {
            // 保持原有头像
            submitData.avatar = userInfo.value.avatar
        }
        
        console.log('提交用户信息:', submitData)
        
        // 调用API更新用户信息
        const res = await updateUserAPI(submitData)
        if (res.code === 200) {
            ElMessage.success('个人信息更新成功')
            // 更新全局用户信息
            await userStore.getInfo()
        } else {
            ElMessage.error(res.msg || '更新失败')
        }
    } catch (error) {
        console.error('表单验证或提交失败:', error)
        ElMessage.error('保存失败，请稍后重试')
    }
}

// 修改密码
const changePassword = async () => {
    if (!passwordFormRef.value) return
    
    try {
        await passwordFormRef.value.validate()
        
        // 调用API修改密码
        const res = await changePasswordAPI({
            oldPassword: passwordForm.oldPassword,
            newPassword: passwordForm.newPassword
        })
        
        if (res.code === 200) {
            ElMessage.success('密码修改成功，请重新登录')
            // 清空表单
            passwordForm.oldPassword = ''
            passwordForm.newPassword = ''
            passwordForm.confirmPassword = ''
            // 登出
            setTimeout(() => {
                userStore.logout()
            }, 1500)
        } else {
            ElMessage.error(res.msg || '密码修改失败')
        }
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

// 确认注销账户
const confirmDeleteAccount = () => {
    ElMessageBox.confirm(
        '您确定要注销账户吗？此操作将永久删除您的账户，且无法恢复！',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        ElMessage({
            type: 'info',
            message: '该功能暂未开放，请联系客服'
        })
    }).catch(() => {
        // 取消操作
    })
}

// 头像上传逻辑
const uploadAvatar = (event) => {
    const file = event.file
    const reader = new FileReader()
    reader.onload = (e) => {
        avatarUrl.value = e.target.result
    }
    reader.readAsDataURL(file)
}

const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) {
        ElMessage.error('上传头像必须是图片格式')
    }
    if (!isLt2M) {
        ElMessage.error('上传头像大小不能超过 2MB')
    }
    return isImage && isLt2M
}

const onImageError = (e) => {
    // 尝试使用默认头像
    const originalSrc = e.target.getAttribute('data-original-src')
    if (originalSrc && e.target.src !== defaultAvatar) {
        console.log('图片加载失败，使用默认头像:', e.target.src, '->', defaultAvatar)
        e.target.src = defaultAvatar
    }
}

// 调试用户角色
const debugUserRoles = () => {
    // 仅在开发环境下显示
    console.log('用户数据:', userInfo.value)
    console.log('用户角色:', userStore.roles || [])
    ElMessage.info(`当前角色: ${userStore.roles?.join(', ') || '无角色'}`)
}

// 我的房源相关数据
const userHouses = ref([])
const houseForm = reactive({
    id: '',
    title: '',
    price: '',
    area: '',
    address: '',
    description: '',
    images: []
})
const houseImageList = ref([])

// 获取用户的房源列表
const fetchUserHouses = async () => {
    try {
        houseLoading.value = true
        console.log('获取用户房源列表')
        
        // 调用API获取当前用户的房源列表
        // 使用URLSearchParams构建查询参数
        const params = new URLSearchParams()
        params.append('current', currentHousePage.value)
        params.append('size', 5)
        // 根据登录用户ID筛选（publisherId是发布者ID字段）
        params.append('publisherId', userInfo.value?.userId || userInfo.value?.id)
        
        // 根据选择的标签页添加状态筛选
        if (houseStatusTab.value !== 'all') {
            params.append('status', houseStatusTab.value)
        }
        
        const res = await getHouseList(params)
        if (res.code === 200) {
            // 转换后端返回的数据格式以适配前端展示
            userHouses.value = res.data.records.map(house => ({
                id: house.houseId,
                title: house.title,
                price: house.price,
                area: house.area + '㎡',
                address: house.address || '未知地址',
                createTime: house.createTime,
                status: house.status, // 状态值保持不变
                rejectReason: house.rejectReason,
                // 如果有图片则使用第一张，否则使用默认图片
                image: house.images && house.images.length > 0 ? house.images[0] : '/src/assets/images/default-house.jpg'
            }))
            totalHouses.value = res.data.total
        } else {
            ElMessage.error(res.msg || '获取房源列表失败')
            userHouses.value = []
        }
    } catch (error) {
        console.error('获取用户房源列表失败:', error)
        ElMessage.error('获取房源列表失败')
        userHouses.value = []
    } finally {
        houseLoading.value = false
    }
}

// 计算过滤后的房源列表
const filteredUserHouses = computed(() => {
  if (houseStatusTab.value === 'all') {
    return userHouses.value;
  }
  return userHouses.value.filter(house => house.status === houseStatusTab.value);
})

// 房源图片上传出错处理
const onHouseImageError = (e) => {
    e.target.src = '/src/assets/images/default-house.jpg'
}

// 房源分页处理
const handleHousePageChange = (page) => {
    currentHousePage.value = page
    fetchUserHouses() // 重新加载数据
}

// 显示上传房源对话框
const showUploadHouseDialog = () => {
    // 直接跳转到房源发布页面
    router.push('/owner/sell')
}

// 关闭对话框前确认
const handleDialogClose = (done) => {
    if (houseForm.title || houseForm.price || houseForm.area || houseForm.address || houseForm.description || houseImageList.value.length > 0) {
        ElMessageBox.confirm('数据未保存，确定要关闭吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            done()
        }).catch(() => {})
    } else {
        done()
    }
}

// 房源图片上传前验证
const beforeHouseImageUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('上传文件只能是图片!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 上传房源图片
const uploadHouseImage = (options) => {
    const { file } = options
    // 这里应该调用实际的上传API
    // 模拟上传成功
    setTimeout(() => {
        // 创建一个临时URL用于预览
        const url = URL.createObjectURL(file)
        houseImageList.value.push({ name: file.name, url })
        houseForm.images.push(url)
        ElMessage.success('图片上传成功')
    }, 500)
}

// 处理图片预览
const handleImagePreview = (file) => {
    previewImageUrl.value = file.url
    imagePreviewVisible.value = true
}

// 处理图片移除
const handleImageRemove = (file, fileList) => {
    houseImageList.value = fileList
    const index = houseForm.images.indexOf(file.url)
    if (index !== -1) {
        houseForm.images.splice(index, 1)
    }
}

// 提交房源表单
const submitHouseForm = async () => {
    if (!houseFormRef.value) return
    
    await houseFormRef.value.validate(async (valid) => {
        if (valid) {
            submitting.value = true
            try {
                // 这里应该调用后端API提交房源
                // const res = await api.submitHouse(houseForm)
                
                // 模拟提交成功
                setTimeout(() => {
                    submitting.value = false
                    uploadHouseDialogVisible.value = false
                    
                    // 如果是编辑模式
                    if (houseForm.id) {
                        const index = userHouses.value.findIndex(h => h.id === houseForm.id)
                        if (index !== -1) {
                            // 更新数据
                            userHouses.value[index] = {
                                ...userHouses.value[index],
                                title: houseForm.title,
                                price: houseForm.price,
                                area: houseForm.area,
                                address: houseForm.address,
                                description: houseForm.description,
                                // 图片更新逻辑
                                status: '0' // 重新变为待审核状态
                            }
                        }
                        ElMessage.success('房源更新成功，等待审核')
                    } else {
                        // 添加新房源
                        const newHouse = {
                            id: Date.now(), // 模拟新ID
                            title: houseForm.title,
                            price: houseForm.price,
                            area: houseForm.area,
                            address: houseForm.address,
                            description: houseForm.description,
                            status: '0', // 待审核
                            createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
                            image: houseForm.images[0] || ''
                        }
                        userHouses.value.unshift(newHouse)
                        ElMessage.success('房源提交成功，等待审核')
                    }
                }, 1000)
            } catch (error) {
                console.error('提交房源失败:', error)
                submitting.value = false
                ElMessage.error('提交失败，请稍后重试')
            }
        }
    })
}

// 查看房源详情
const viewHouseDetail = (house) => {
    // 跳转到房源详情页
    router.push(`/house/${house.id}`)
}

// 编辑房源
const editHouse = (house) => {
    // 填充表单数据
    houseForm.id = house.id
    houseForm.title = house.title
    houseForm.price = house.price
    houseForm.area = house.area
    houseForm.address = house.address
    houseForm.description = house.description || ''
    
    // 清空图片列表
    houseImageList.value = []
    houseForm.images = []
    
    // 如果有图片，添加到列表中
    if (house.image) {
        houseImageList.value.push({ name: 'current', url: house.image })
        houseForm.images.push(house.image)
    }
    
    // 显示对话框
    uploadHouseDialogVisible.value = true
}

// 删除房源
const removeHouse = (house) => {
    ElMessageBox.confirm(`确定要删除房源 "${house.title}" 吗？此操作不可恢复！`, '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteHouse(house.id)
            if (res.code === 200) {
                ElMessage.success('房源删除成功')
                // 重新加载列表
                fetchUserHouses()
            } else {
                ElMessage.error(res.msg || '删除失败')
            }
        } catch (error) {
            console.error('删除房源失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }).catch(() => {
        // 取消删除
    })
}

// 保留一些可能需要的isAdmin和isAgent计算属性，因为它们可能在其他地方被使用
// 这些属性只在这里定义，不会被任何地方使用，可以作为辅助函数保留
const isAdmin = computed(() => {
    return (userStore.roles || []).includes('admin')
})

const isAgent = computed(() => {
    return (userStore.roles || []).includes('agent')
})

// 导航到管理界面
const navigateTo = (path) => {
    router.push(path)
}

// 获取用户信息
const getUserInfo = async () => {
    try {
        // 这里应该是从store或API获取用户信息的逻辑
        console.log('获取用户信息')
    } catch (error) {
        console.error('获取用户信息失败:', error)
    }
}

// 处理房源状态标签切换
const handleTabChange = () => {
  console.log('切换到标签:', houseStatusTab.value)
  // 不需要调用API，直接使用本地过滤即可
  // fetchUserHouses() 
}
</script>

<style scoped>
.profile-page {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.content-wrapper {
    flex: 1;
    padding: 40px 0;
}

.profile-container {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    gap: 30px;
}
    
    .profile-sidebar {
    width: 250px;
        flex-shrink: 0;
}
        
        .profile-info {
    background-color: #fff;
            border-radius: 8px;
            padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            text-align: center;
}
            
            .avatar {
                margin-bottom: 15px;
            }
            
.user-details h3 {
    margin: 10px 0;
                    font-size: 18px;
                    color: #333;
                }
                
.user-details p {
                    margin: 5px 0;
                    color: #666;
                    font-size: 14px;
        }
        
        .menu-list {
    background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
            
            .menu-item {
    padding: 15px 20px;
                display: flex;
                align-items: center;
                cursor: pointer;
                transition: all 0.3s;
    border-bottom: 1px solid #f0f0f0;
}

.menu-item:last-child {
    border-bottom: none;
}

.menu-item:hover {
    background-color: #f5f7fa;
}

.menu-item.active {
    background-color: #ecf5ff;
                    color: #409EFF;
                }
                
.menu-item .el-icon {
                    margin-right: 10px;
                    font-size: 18px;
    }
    
    .profile-main {
        flex: 1;
    background-color: #fff;
        border-radius: 8px;
        padding: 30px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
        
.tab-content h2 {
            margin-top: 0;
            margin-bottom: 20px;
    font-size: 22px;
    color: #333;
    border-bottom: 1px solid #eee;
            padding-bottom: 15px;
}

.avatar-uploader-container {
    display: flex;
    align-items: center;
}

.avatar-uploader :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.avatar-preview {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
}

.avatar-tips {
    margin-left: 20px;
    color: #666;
    font-size: 14px;
}

.avatar-tips p {
    margin: 5px 0;
}

.account-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
    
.account-option h3 {
    margin-top: 0;
    margin-bottom: 5px;
        font-size: 16px;
    }
    
.account-option p {
        margin: 0;
        color: #666;
        font-size: 14px;
    }

/* 我的房源相关样式 */
.myhouses-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.user-house-list {
    margin-top: 20px;
}

.house-card {
    margin-bottom: 15px;
}

.house-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.house-title {
    font-size: 18px;
    font-weight: bold;
}

.house-info {
    display: flex;
    margin-bottom: 15px;
}

.house-image {
    width: 120px;
    height: 90px;
    overflow: hidden;
    margin-right: 15px;
    border-radius: 4px;
}

.house-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.house-details {
    flex: 1;
}

.house-price {
    color: #f56c6c;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

.house-area, .house-address, .house-time {
    color: #606266;
    margin-bottom: 5px;
    font-size: 14px;
}

.house-reject-reason {
    color: #f56c6c;
    margin-top: 5px;
    font-size: 14px;
}

.house-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: center;
}

.house-status-tabs {
    margin-bottom: 20px;
}

/* 管理中心样式 */
.management-panel {
    margin-top: 20px;
}

.management-card {
    height: 170px;
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.3s;
}

.management-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.management-card-content {
    height: 100%;
    display: flex;
        flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 20px 10px;
}

.management-icon-wrapper {
    width: 60px;
    height: 60px;
    background-color: #f0f5ff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
}

.management-card-content h3 {
    margin: 0 0 10px;
    font-size: 18px;
}

.management-card-content p {
    margin: 0;
    color: #666;
    font-size: 14px;
}
</style> 